package com.cy.metrics;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.cy.util.U;
import org.testng.annotations.Test;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * https://metrics.dropwizard.io/3.1.0/
 * @author yue.cao
 * @since 12-29-2020
 */
public class CounterDemo {


	@Test(description = "Meter 工具  用于计次")
	public void testMeter() throws InterruptedException {
		BlockingDeque<Long> queue = new LinkedBlockingDeque<>(1000);
		MetricRegistry registry = new MetricRegistry();

		Counter counter = registry.counter("queue-size", Counter::new);

		ConsoleReporter reporter = ConsoleReporter
				.forRegistry(registry)
				.convertRatesTo(TimeUnit.SECONDS)
				.convertDurationsTo(TimeUnit.SECONDS)
				.build();

		reporter.start(1, TimeUnit.SECONDS);

		new Thread(new Runnable() {
			@Override
			public void run() {

				while (true) {
					U.sleepRandom();
					queue.add(System.currentTimeMillis());
					counter.inc();
				}
			}
		}).start();
		new Thread(() -> {
			while (true) {
				U.sleepRandom();
				if (queue.poll() != null) {
					counter.dec();
				}
			}
		}).start();
		TimeUnit.SECONDS.sleep(10);
	}


}
